<template>
  <div class="tools-panel">
    <div class="panel-header">
      <h3>工具设置</h3>
    </div>
    
    <div v-if="!hasCurrentConversation" class="no-conversation">
      <el-empty description="请选择一个对话进行编辑" />
    </div>
    
    <div v-else class="panel-content">
      <!-- 系统提示设置 -->
      <el-card class="section-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>系统提示 (System Prompt)</span>
            <el-switch 
              v-model="hasSystemPrompt" 
              @change="toggleSystemPrompt"
              size="small"
            />
          </div>
        </template>
        
        <div v-if="hasSystemPrompt" class="system-prompt-section">
          <el-input
            v-model="systemPrompt"
            type="textarea"
            :rows="6"
            placeholder="输入系统提示内容..."
            @blur="updateSystemPrompt"
            resize="vertical"
          />
          <div class="prompt-tips">
            <el-text size="small" type="info">
              系统提示定义AI的行为和角色。留空表示使用默认设置。
            </el-text>
          </div>
        </div>
        
        <div v-else class="empty-section">
          <el-text type="info">未启用系统提示</el-text>
        </div>
      </el-card>

      <!-- 工具定义设置 -->
      <el-card class="section-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>工具定义 (Tools)</span>
            <el-switch 
              v-model="hasTools" 
              @change="toggleTools"
              size="small"
            />
          </div>
        </template>
        
        <div v-if="hasTools" class="tools-section">
          <el-input
            v-model="toolsJson"
            type="textarea"
            :rows="8"
            placeholder="输入工具定义JSON..."
            @blur="updateToolsJson"
            resize="vertical"
          />
          <div class="tools-tips">
            <el-text size="small" type="info">
              工具定义必须是有效的JSON数组格式。每个工具包含name、description和parameters字段。
            </el-text>
          </div>
        </div>
        
        <div v-else class="empty-section">
          <el-text type="info">未启用工具定义</el-text>
        </div>
      </el-card>

      <!-- 快速操作 -->
      <el-card class="section-card" shadow="never">
        <template #header>
          <span>快速操作</span>
        </template>
        
        <div class="quick-actions">
          <div class="button-wrapper">
            <el-button 
              type="primary" 
              :icon="DocumentCopy"
              @click="copyConversation"
              size="small"
            >
              复制对话
            </el-button>
          </div>
          
          <div class="button-wrapper">
            <el-button 
              type="warning" 
              :icon="Refresh"
              @click="resetConversation"
              size="small"
            >
              重置对话
            </el-button>
          </div>
          
          <div class="button-wrapper">
            <el-button 
              type="success" 
              :icon="CircleCheck"
              @click="validateConversation"
              size="small"
            >
              验证格式
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 重置确认对话框 -->
    <el-dialog
      v-model="resetDialogVisible"
      title="重置确认"
      width="450px"
      :close-on-click-modal="false"
      @close="handleResetDialogClose"
    >
      <div class="reset-dialog-content">
        <el-icon class="warning-icon" color="#E6A23C" size="24px">
          <WarningFilled />
        </el-icon>
        <div class="reset-message">
          {{ resetDialogMessage }}
        </div>
      </div>
      
      <template #footer>
        <div v-if="resetDialogType === 'unsaved'" class="dialog-footer-three">
          <el-button @click="handleResetAction('cancel')" size="default">
            取消
          </el-button>
          <el-button @click="handleResetAction('direct')" type="warning" size="default">
            直接重置
          </el-button>
          <el-button @click="handleResetAction('save')" type="primary" size="default">
            保存并重置
          </el-button>
        </div>
        <div v-else class="dialog-footer-two">
          <el-button @click="handleResetAction('cancel')" size="default">
            取消
          </el-button>
          <el-button @click="handleResetAction('confirm')" type="danger" size="default">
            确认重置
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useDatasetStore } from '../../stores/dataset.js'
import { useConversationStore } from '../../stores/conversation.js'
import { ElMessage } from 'element-plus'
import { DocumentCopy, Refresh, CircleCheck, WarningFilled } from '@element-plus/icons-vue'

const datasetStore = useDatasetStore()
const conversationStore = useConversationStore()

// 响应式数据
const systemPrompt = ref('')
const toolsJson = ref('')

// 重置对话框相关数据
const resetDialogVisible = ref(false)
const resetDialogMessage = ref('')
const resetDialogType = ref('simple') // 'simple' 或 'unsaved'

// 计算属性
const hasCurrentConversation = computed(() => {
  return conversationStore.currentConversationIndex >= 0 && 
         conversationStore.currentConversation !== null
})

const hasSystemPrompt = computed({
  get() {
    const conversation = conversationStore.currentConversation
    return conversation && !!conversation.system
  },
  set(value) {
    // 通过 toggleSystemPrompt 方法处理
  }
})

const hasTools = computed({
  get() {
    const conversation = conversationStore.currentConversation
    return conversation && !!conversation.tools
  },
  set(value) {
    // 通过 toggleTools 方法处理
  }
})



// 监听当前对话变化
watch(() => conversationStore.currentConversation, (conversation) => {
  if (conversation) {
    loadConversationData(conversation)
  }
}, { immediate: true, deep: true })

// 方法
const loadConversationData = (conversation) => {
  // 加载系统提示词
  systemPrompt.value = conversation.system || ''
  
  // 加载工具定义
  if (conversation.tools) {
    try {
      const tools = JSON.parse(conversation.tools)
      
      // 检查是否是标准ShareGPT格式（带有type和function字段）
      if (Array.isArray(tools) && tools.length > 0 && tools[0].type === 'function') {
        // 转换为简化格式供编辑
        const simplifiedTools = tools.map(tool => ({
          name: tool.function.name,
          description: tool.function.description,
          parameters: tool.function.parameters
        }))
        toolsJson.value = JSON.stringify(simplifiedTools, null, 2)
      } else {
        // 已经是简化格式
        toolsJson.value = JSON.stringify(tools, null, 2)
      }
    } catch (e) {
      console.error('解析工具定义失败:', e)
      toolsJson.value = ''
    }
  } else {
    toolsJson.value = ''
  }
}

const toggleSystemPrompt = (enabled) => {
  const conversation = conversationStore.currentConversation
  if (!conversation) return
  
  if (enabled) {
    conversation.system = systemPrompt.value || '你是一个有用的AI助手。'
    systemPrompt.value = conversation.system
  } else {
    conversation.system = ''
    systemPrompt.value = ''
  }
  
  datasetStore.markAsModified()
}

const updateSystemPrompt = () => {
  const conversation = conversationStore.currentConversation
  if (conversation) {
    conversation.system = systemPrompt.value
    datasetStore.markAsModified()
  }
}

const toggleTools = (enabled) => {
  const conversation = conversationStore.currentConversation
  if (!conversation) return
  
  if (enabled) {
    if (!toolsJson.value) {
      toolsJson.value = JSON.stringify([
        {
          name: 'example_function',
          description: 'An example function',
          parameters: {
            type: 'object',
            properties: {},
            required: []
          }
        }
      ], null, 2)
    }
    updateToolsJson()
  } else {
    conversation.tools = ''
    toolsJson.value = ''
  }
  
  datasetStore.markAsModified()
}

const updateToolsJson = () => {
  const conversation = conversationStore.currentConversation
  if (!conversation) return
  
  try {
    if (toolsJson.value.trim()) {
      // 验证JSON格式
      const tools = JSON.parse(toolsJson.value)
      if (Array.isArray(tools)) {
        conversation.tools = JSON.stringify(tools)
      } else {
        throw new Error('工具定义必须是数组格式')
      }
    } else {
      conversation.tools = ''
    }
    datasetStore.markAsModified()
  } catch (e) {
    console.error('更新工具定义失败:', e)
    ElMessage.error('工具定义JSON格式错误: ' + e.message)
  }
}



const copyConversation = () => {
  const conversation = conversationStore.currentConversation
  if (conversation) {
    datasetStore.addConversation(JSON.parse(JSON.stringify(conversation)))
    ElMessage.success('对话已复制')
  }
}

const resetConversation = () => {
  // 检查是否有未保存的更改
  if (datasetStore.hasUnsavedChanges) {
    resetDialogType.value = 'unsaved'
    resetDialogMessage.value = '重置将清空当前对话的所有内容和设置，此操作不可撤销。\n\n当前数据集有未保存的更改，是否要先保存？'
  } else {
    resetDialogType.value = 'simple'
    resetDialogMessage.value = '重置将清空当前对话的所有内容和设置，此操作不可撤销。'
  }
  
  resetDialogVisible.value = true
}

// 处理重置对话框的操作
const handleResetAction = async (action) => {
  resetDialogVisible.value = false
  
  if (action === 'cancel') {
    return // 取消操作
  }
  
  try {
    if (action === 'save') {
      // 用户选择保存并重置
      if (datasetStore.currentDataset.filePath) {
        await datasetStore.saveDataset()
      } else {
        const { save } = await import('@tauri-apps/plugin-dialog')
        
        const filePath = await save({
          title: '保存当前数据集',
          defaultPath: datasetStore.currentDataset.name + '.json',
          filters: [{
            name: 'JSON 数据集',
            extensions: ['json']
          }]
        })
        
        if (!filePath) {
          return // 用户取消了保存，不继续重置
        }
        
        await datasetStore.saveDataset(filePath)
      }
      ElMessage.success('数据集已保存')
    }
    
    // 执行重置
    if (action === 'confirm' || action === 'direct' || action === 'save') {
      const conversation = conversationStore.currentConversation
      if (conversation) {
        conversation.conversations = [
          { from: 'human', value: '' },
          { from: 'gpt', value: '' }
        ]
        conversation.system = ''
        conversation.tools = ''
        datasetStore.markAsModified()
        loadConversationData(conversation)
        ElMessage.success('对话已重置')
      }
    }
  } catch (error) {
    console.error('重置操作失败:', error)
    ElMessage.error('重置操作失败: ' + error.message)
  }
}

// 处理对话框关闭（点击X或ESC）
const handleResetDialogClose = () => {
  resetDialogVisible.value = false
}

const validateConversation = () => {
  const conversation = conversationStore.currentConversation
  if (conversation) {
    const result = conversationStore.validateConversationStructure(conversation.conversations || [])
    if (result.isValid) {
      ElMessage.success('对话格式正确')
    } else {
      ElMessage.error('对话格式有误，请检查错误信息')
    }
  }
}
</script>

<style scoped>
.tools-panel {
  height: 100%;
  padding: 16px;
  display: flex;
  flex-direction: column;
}

.panel-header {
  margin-bottom: 16px;
}

.panel-header h3 {
  margin: 0;
  color: #303133;
}

.panel-content {
  flex: 1;
  overflow-y: auto;
}

.section-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-section {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.prompt-tips {
  margin-top: 8px;
}

.tools-tips {
  margin-top: 8px;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: stretch; /* 确保按钮填满容器宽度 */
}

/* 按钮包装器样式 */
.quick-actions .button-wrapper {
  width: 100%;
  display: flex;
}

/* 使用深层选择器覆盖Element Plus按钮内部样式 */
.quick-actions .button-wrapper :deep(.el-button) {
  width: 100% !important; /* 确保所有按钮宽度一致 */
  justify-content: flex-start !important; /* 内容左对齐 */
  text-align: left !important;
}

/* 覆盖按钮内部span的样式 */
.quick-actions .button-wrapper :deep(.el-button span) {
  display: flex !important;
  align-items: center !important;
  justify-content: flex-start !important;
  width: 100% !important;
}

/* 图标和文字间距 */
.quick-actions .button-wrapper :deep(.el-button .el-icon) {
  margin-right: 6px !important;
}

/* 确保按钮文字左对齐 */
.quick-actions .button-wrapper :deep(.el-button .el-button__text-wrapper) {
  flex: 1;
  text-align: left;
}

.no-conversation {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.reset-dialog-content {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px 0;
}

.warning-icon {
  flex-shrink: 0;
  margin-top: 2px;
}

.reset-message {
  flex: 1;
  font-size: 14px;
  line-height: 1.5;
  color: #606266;
  white-space: pre-line;
}

.dialog-footer-three {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.dialog-footer-two {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style> 